<template>
  <div class="dicom-uploader">
    <el-card class="upload-card">
      <template #header>
        <div class="card-header">
          <span>DICOM文件上传</span>
        </div>
      </template>
      
      <el-upload
        class="upload-demo"
        drag
        :auto-upload="false"
        :on-change="handleChange"
        :on-remove="handleRemove"
        :file-list="fileList"
        accept=".dcm"
        multiple
      >
        <el-icon class="el-icon--upload">
          <UploadFilled />
        </el-icon>
        <div class="el-upload__text">
          将文件拖到此处，或<em>点击上传</em>
        </div>
        <template #tip>
          <div class="el-upload__tip">
            请上传DICOM格式文件，支持多文件上传
          </div>
        </template>
      </el-upload>
      
      <div class="upload-actions">
        <el-button 
          type="primary" 
          @click="submitUpload" 
          :disabled="fileList.length === 0 || uploading"
          :loading="uploading"
        >
          {{ uploading ? '上传中...' : '开始上传' }}
        </el-button>
        <el-button @click="clearFiles" :disabled="fileList.length === 0">
          清空列表
        </el-button>
      </div>
      
      <!-- 上传进度显示 -->
      <div v-if="uploadProgress.length > 0" class="progress-container">
        <div 
          v-for="progress in uploadProgress" 
          :key="progress.filename"
          class="progress-item"
        >
          <div class="progress-info">
            <span class="filename">{{ progress.filename }}</span>
            <span class="status">{{ getProgressStatus(progress.status) }}</span>
          </div>
          <el-progress 
            :percentage="progress.percentage" 
            :status="getProgressType(progress.status)"
          />
        </div>
      </div>
    </el-card>
  </div>
</template>

<script setup>
import { ref, reactive } from 'vue'
import { UploadFilled } from '@element-plus/icons-vue'
import { ElMessage } from 'element-plus'
import api from '@/utils/api'

const fileList = ref([])
const uploading = ref(false)
const uploadProgress = ref([])

// 处理文件选择变化
const handleChange = (file, files) => {
  fileList.value = files
}

// 处理文件移除
const handleRemove = (file, files) => {
  fileList.value = files
}

// 清空文件列表
const clearFiles = () => {
  fileList.value = []
  uploadProgress.value = []
}

// 获取进度状态文本
const getProgressStatus = (status) => {
  switch (status) {
    case 'uploading': return '上传中...'
    case 'processing': return '处理中...'
    case 'completed': return '已完成'
    case 'failed': return '失败'
    default: return '等待上传'
  }
}

// 获取进度条类型
const getProgressType = (status) => {
  switch (status) {
    case 'completed': return 'success'
    case 'failed': return 'exception'
    default: return null
  }
}

// 提交上传
const submitUpload = async () => {
  if (fileList.value.length === 0) {
    ElMessage.warning('请先选择要上传的文件')
    return
  }

  uploading.value = true
  uploadProgress.value = fileList.value.map(file => ({
    filename: file.name,
    percentage: 0,
    status: 'uploading'
  }))

  try {
    // 逐个上传文件
    for (let i = 0; i < fileList.value.length; i++) {
      const file = fileList.value[i]
      await uploadSingleFile(file, i)
    }
    
    ElMessage.success('所有文件上传完成')
  } catch (error) {
    ElMessage.error('上传过程中出现错误: ' + error.message)
  } finally {
    uploading.value = false
  }
}

// 上传单个文件
const uploadSingleFile = async (file, index) => {
  try {
    // 更新状态为上传中
    uploadProgress.value[index].status = 'uploading'
    
    // 创建FormData
    const formData = new FormData()
    formData.append('file', file.raw)
    
    // 上传文件
    const response = await api.uploadFile(formData)
    
    // 更新状态为处理中
    uploadProgress.value[index].status = 'processing'
    uploadProgress.value[index].percentage = 50
    
    // 轮询检查处理状态
    await pollProcessingStatus(response.filename, index)
    
  } catch (error) {
    uploadProgress.value[index].status = 'failed'
    uploadProgress.value[index].percentage = 100
    throw error
  }
}

// 轮询检查处理状态
const pollProcessingStatus = async (filename, index) => {
  const maxAttempts = 30 // 最大尝试次数
  const interval = 2000 // 轮询间隔2秒
  
  for (let attempt = 0; attempt < maxAttempts; attempt++) {
    try {
      const statusResponse = await api.getUploadStatus(filename)
      
      if (statusResponse.status === 'completed') {
        uploadProgress.value[index].status = 'completed'
        uploadProgress.value[index].percentage = 100
        return
      } else if (statusResponse.status === 'failed') {
        uploadProgress.value[index].status = 'failed'
        uploadProgress.value[index].percentage = 100
        throw new Error(statusResponse.message || '处理失败')
      }
      
      // 更新进度（处理中状态保持在50-90%之间）
      const progress = 50 + Math.min(40, Math.floor((attempt / maxAttempts) * 40))
      uploadProgress.value[index].percentage = progress
      
      // 等待下一次轮询
      await new Promise(resolve => setTimeout(resolve, interval))
    } catch (error) {
      if (attempt === maxAttempts - 1) {
        uploadProgress.value[index].status = 'failed'
        uploadProgress.value[index].percentage = 100
        throw error
      }
    }
  }
  
  // 超时处理
  uploadProgress.value[index].status = 'failed'
  uploadProgress.value[index].percentage = 100
  throw new Error('处理超时')
}
</script>

<style scoped>
.dicom-uploader {
  max-width: 800px;
  margin: 20px auto;
}

.upload-card {
  border-radius: 8px;
  box-shadow: 0 2px 12px 0 rgba(0, 0, 0, 0.1);
}

.card-header {
  display: flex;
  justify-content: space-between;
  align-items: center;
  font-size: 18px;
  font-weight: 600;
}

.upload-demo {
  margin-bottom: 20px;
}

.upload-actions {
  display: flex;
  gap: 10px;
  justify-content: center;
  margin-bottom: 20px;
}

.progress-container {
  margin-top: 20px;
}

.progress-item {
  margin-bottom: 15px;
  padding: 10px;
  border: 1px solid #ebeef5;
  border-radius: 4px;
  background-color: #fafafa;
}

.progress-info {
  display: flex;
  justify-content: space-between;
  margin-bottom: 8px;
  font-size: 14px;
}

.filename {
  font-weight: 500;
  color: #606266;
}

.status {
  color: #909399;
}

.el-progress {
  margin-top: 5px;
}
</style>